package com.jiuyuan.service.impl;

import com.jiuyuan.config.security.JWTTokenUtils;
import com.jiuyuan.entity.vo.RespBean;
import com.jiuyuan.entity.vo.RespBeanEnum;
import com.jiuyuan.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: hrms
 * @description:
 * @author: Feng
 * @create: 2023-02-15 09:27
 **/

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest req) {
        //验证码判断
        String kaptcha = (String) req.getSession().getAttribute("kaptcha");
        if(null == code || !code.equals(kaptcha)){
            return RespBean.error(RespBeanEnum.CAPTCHA_ERROR);
        }

        //判断数据合法
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        //加密密码在后面
        if(userDetails==null || !passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        if(!userDetails.isEnabled()) return RespBean.error(RespBeanEnum.NOT_ENABLED);

        //用户放入securityContext中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //返回token和tokenHead
        Map<String,String> resultMap = new HashMap<>();
        String token = JWTTokenUtils.createTokenByUserDetails(userDetails);
        resultMap.put("token",token);
        resultMap.put("tokenHead",tokenHead);

        return RespBean.success("登录成功",resultMap);
    }
}
